<?php
namespace App\Http\Controllers;

use App\Models\Activity;
use App\Models\Game;
use App\Models\GameWinners;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as lPaginator;

class GameWinnersController extends CommonController
{
    /**
     *获取获取列表
     */
    public function getIndex()
    {
        $lists = GameWinners::with('prize.game.activity', 'prize.game.type')->orderBy('prize_id', 'desc')->paginate(10);

        return view('gamewinners.index')->with("lists", $lists)->with("actions", $this->actions);
    }

    /**
     *执行一个搜索
     */
    public function search(Request $request)
    {
        $data = $request->input();
        $lists = GameWinners::with('prize.game.activity', 'prize.game.type')->orderBy('prize_id', 'desc')->get();

        if(isset($data['subject']) && $data['subject']!=''){
            $saIds = Activity::where('subject', 'like', '%'.trim($data['subject']).'%')->lists('id')->toArray();
            $newLists=array();
            foreach($lists as $k=>$v){
                if(isset($v->prize->game->activity->id) && in_array($v->prize->game->activity->id, $saIds)){
                    $newLists[] = $v;
                }
            }
            $lists = $newLists;
        }

        if(isset($data['game_name']) && $data['game_name']!=''){
            $gIds = Game::where('title', 'like', '%'.trim($data['game_name']).'%')->lists('id')->toArray();
            $gLists = array();
            foreach($lists as $k=>$v){
                if(isset($v->prize->game->id) && in_array($v->prize->game->id, $gIds)){
                    $gLists[] = $v;
                }
            }
            $lists = $gLists;
        }

        $page = $request->input('page') ? $request->input('page') : 1;
        $paginator = new lPaginator(
            array_slice($lists, ($page - 1)*10, 10), count($lists), 10, $page, [
            'path'  => 'search',
            'query' => array('subject' => trim($data['subject']), 'game_name' => trim($data['game_name'])),
        ]);

        return view('gamewinners.search')->with("lists", $paginator)->with("actions", $this->actions);
    }


    /**
     * 获取编辑页面
     */
    public function getEdit(Request $request)
    {
        $data = $request->input();
        $list = GameWinners::where('id', $data['id'])->first();

        return view('gamewinners.edit')->with('list', $list);
    }

    /**
     * 执行一个编辑
     */
    public function postEdit(Request $request)
    {
        $data = $request->input();

        GameWinners::where('id', $data['id'])->update(['tel'=>$data['tel'], 'name'=>$data['name']]);

        return AjaxCallbackMessage('编辑成功', true, url('gamewinners/index'));
    }
}